package com.jinx.zookeeper.lock;

import org.apache.zookeeper.AddWatchMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 *  测试分布式锁
 * @author Jinx
 * @date 2021/6/14 17:34
 */
public class Abandon {

    /**
     *  共享资源  假设他是redis
     */
    private static int count = 0;
    private final ZookeeperDistributedLock lock = new ZookeeperDistributedLock();




    @SuppressWarnings("all")
    public static void main(String[] args) throws IOException, InterruptedException {
        System.out.println("*************** 开始了 ***************");
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                new Abandon().addCount();
                System.out.println("当前count： \t " + count);
            }).start();
        }

        new Abandon().addWatcher();
        System.in.read();
    }


    private void addCount(){
        lock.lock();
        try {
            TimeUnit.MILLISECONDS.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        count++;
        lock.unLock();
    }


    private void addWatcher(){
        try {
            lock.zooKeeper.addWatch("/lxx", watchedEvent -> {
                if (watchedEvent.getType() == Watcher.Event.EventType.NodeDeleted) {
                    System.out.println("删除事件来咯   ");
                }else {
                    // 其他的事件不处理  重新添加事件
                    System.out.println("其他事件");
                }
            }, AddWatchMode.PERSISTENT);
        } catch (KeeperException | InterruptedException ignored) {

        }
    }
}
